package marshall;

import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.ByteInput;

import java.io.IOException;

public class ChannelBufferByteInput implements ByteInput {

    private final ByteBuf byteBuf;

    public ChannelBufferByteInput(ByteBuf byteBuf){
        this.byteBuf = byteBuf;
    }

    public int read() throws IOException {
        if (byteBuf.isReadable()){
            return byteBuf.readByte() & 0xff;
        }
        return -1;
    }

    public int read(byte[] bytes) throws IOException {
        return read(bytes,0,bytes.length);
    }

    public int read(byte[] bytes, int dstIndex, int length) throws IOException {
        int available = available();
        if (available == 0){
            return -1;
        }
        length = Math.min(available,length);
        byteBuf.readBytes(byteBuf,dstIndex,length);
        return length;
    }

    public int available() throws IOException {
        return 0;
    }

    public long skip(long l) throws IOException {
        int readable = byteBuf.readableBytes();
        if (readable < l){
            l = readable;
        }
        byteBuf.readerIndex((int) (byteBuf.readerIndex() + l));
        return l;
    }

    public void close() throws IOException {

    }
}
